package com.itheima.web.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.Result;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class BaseServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //1.获取请求标记
            String pathInfo = req.getPathInfo().substring(1);
            //2.反射获取当前对象要执行的方法对象
            Method method = this.getClass().getDeclaredMethod(pathInfo,HttpServletRequest.class,HttpServletResponse.class);
            //3.开启访问权限(暴力反射)
            method.setAccessible(true);
            //4.反射执行方法
            Object result = method.invoke(this, req, resp);
            //5.统一响应json结果
            objectMapper.writeValue(resp.getOutputStream(),result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
